package com.bdqn.service.impl;
import	java.awt.SystemColor;

import com.bdqn.component.ArticleStatus;
import com.bdqn.component.BlogConstants;
import com.bdqn.component.SensitivewordFilter;
import com.bdqn.dao.ArticleCheckMapper;
import com.bdqn.dao.ArticleMapper;
import com.bdqn.dao.ImagesMapper;
import com.bdqn.entity.*;
import com.bdqn.service.ArticleService;
import com.bdqn.thread.SensitivewordFilterThead;
import com.bdqn.util.FileResult;
import com.bdqn.util.FileUtil;
import com.bdqn.util.Page;
import com.bdqn.util.Result;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import scala.annotation.meta.param;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;

@Service("articleService")
public class ArticleServiceImpl implements ArticleService {
    @Autowired
    private ArticleMapper articleMapper;
    @Autowired
    private ArticleCheckMapper articleCheckMapper;
    @Autowired
    private SensitivewordFilter sensitivewordFilter;
    @Autowired
    private DataSourceTransactionManager transactionManager;

    @Autowired
    private ImagesMapper imagesMapper;

    /**
     * 分页
     *
     * @param tid
     * @param pageIndex
     * @param pageSize
     * @return
     */
    @Override
    public Result<Page<Article>> getPageArticles(Integer tid, Integer pageIndex, Integer pageSize) {
        Page<Article> page = new Page<Article>(pageIndex, pageSize);
        page.setCount(articleMapper.selectCount(tid, 0));
        page.setDataList(articleMapper.selectList(tid, 0, (pageIndex - 1) * pageSize, pageSize));
        return Result.createSuccess(page);
    }


    /**
     * 富文本的文件上传
     *
     * @param request
     * @param file
     * @return
     */
    @Override
    public Map<String, Object> uploadArticleImg(HttpServletRequest request, CommonsMultipartFile file) {

        String newFileName = request.getSession().getId() + "_article";
        FileResult fs = FileUtil.saveFileToPath(request, file, BlogConstants.ARTICLE_SAVE_PATH, BlogConstants.ARTICLE_MAPPING_URL, newFileName);
        Map<String, Object> map = new HashMap<String, Object>();
        if (fs != null) {
            List<String> list = (List<String>) request.getSession().getAttribute("tempArticleFname");
            if (list == null) {
                list = new ArrayList<>();
            }
            list.add(fs.getFileName());
            request.getSession().setAttribute("tempArticleFname", list);
            map.put("code", 0);
            Map<String, Object> map1 = new HashMap<String, Object>();
            map1.put("src", fs.getHttpUrl());
            map.put("data", map1);
        } else {
            map.put("code", 1);
            map.put("msg", "图片上传失败");
        }

        return map;
    }


    @Override
    public Result editArticle(
        String flag, ArticleWithBLOBs article,
        CommonsMultipartFile file, HttpServletRequest request) {
        //增加
        FileResult rs = null;
        System.out.println(article != null);
        System.out.println(article.getType() == 0);
        if (article != null && article.getType() == 0) {
            if (!Arrays.asList("status", "delete", "draft").contains(flag)) {
                if (file != null) {
                    rs = FileUtil.saveFileToPath(request, file, BlogConstants.ARTICLE_SAVE_PATH, BlogConstants.ARTICLE_MAPPING_URL);
                }
                if (rs == null && !"update".equals(flag)) {
                    return Result.createError("发布失败,无法保存图片");
                }
            }
        }
        UserWithBLOBs loginUser = (UserWithBLOBs) request.getSession().getAttribute(BlogConstants.LOGIN_SESSION_KEY);

        if ("add".equals(flag) || "update".equals(flag)) {
            if (article.getType() == 0) {
                if (article == null || StringUtils.isBlank(article.getTitle()) || StringUtils.isBlank(article.getSummary()) || article.getArticletypeid() == null) {
                    return Result.createError("参数错误");
                }
                if ("update".equals(flag) && StringUtils.isBlank(article.getUuid())) {
                    return Result.createError("参数错误");
                }

            } else {
                if (StringUtils.isBlank(article.getContent())) {
                    return Result.createError("参数错误");
                }

            }
            if (rs != null) {
                article.setCover(rs.getHttpUrl());
            }
            if ("add".equals(flag)) {
                article.setUuid(UUID.randomUUID().toString().replace("-", "").toUpperCase());
                article.setAwesome(0);
                article.setReader(0);
                article.setCreatetime(new Date());
                article.setUserId(loginUser.getUuid());
            }
            //原本想设置状态
            Integer originStatus = article.getStatus();
            //设置待审核状态
            article.setStatus(ArticleStatus.IN_AUDIT.getValue());

            int count = "add".equals(flag) ? articleMapper.insertSelective(article) : articleMapper.updateByPrimaryKeySelective(article);

            if (count > 0) {
                request.getSession().removeAttribute("tempArticleFname");
                //准备审核
                SensitivewordFilterThead thead = new SensitivewordFilterThead(sensitivewordFilter, article,
                    originStatus, articleCheckMapper, articleMapper, transactionManager);

                thead.start();

                return Result.createSuccess("发布成功!审核通过后才会显示!");
            }
            if (rs.getFile().exists()) {
                rs.getFile().delete();
            }
            return Result.createError("操作失败");

        }
        //修改封面
        else if ("cover".equals(flag)) {

            if (article == null || article.getUuid() == null) {
                return Result.createError("参数错误");
            }
            article.setCover(rs.getHttpUrl());
            if (articleMapper.selectCountByIdAndUserId(article.getUuid(), loginUser.getUuid()) == 0) {
                return Result.createError("您没有权限操作");
            }
            if (articleMapper.updateByPrimaryKeySelective(article) > 0) {
                return Result.createSuccess("修改封面成功");
            }

            //重置状态
        } else if ("status".equals(flag)) {
            if (article == null || article.getUuid() == null || article.getStatus() == null) {
                return Result.createError("参数错误");
            }

            if (articleMapper.selectCountByIdAndUserId(article.getUuid(), loginUser.getUuid()) == 0) {
                return Result.createError("您没有权限操作");
            }

            Integer originStatus = article.getStatus();
            if (articleMapper.updateByPrimaryKeySelective(article) > 0) {
                ArticleWithBLOBs newArticle = articleMapper.selectByPrimaryKey(article.getUuid());
                //准备审核
                SensitivewordFilterThead thead = new SensitivewordFilterThead(sensitivewordFilter, newArticle,
                    originStatus, articleCheckMapper, articleMapper, transactionManager);

                thead.start();
                return Result.createSuccess("状态重置成功,等待审核");
            } else {
                return Result.createError("重置失败");
            }


            //移送草稿箱
        } else if ("draft".equals(flag)) {
            if (StringUtils.isBlank(article.getUuid())) {
                return Result.createError("参数错误");
            }
            article.setStatus(ArticleStatus.DRAFTS.getValue());
            if (articleMapper.updateByPrimaryKeySelective(article) > 0) {
                return Result.createSuccess("移除成功，可以在草稿箱里恢复");
            } else {
                return Result.createError("移除失败");
            }
            //删除
        } else if ("delete".equals(flag)) {
            if (StringUtils.isBlank(article.getUuid())) {
                return Result.createError("参数错误");
            }

            if (articleCheckMapper.deleteByArticleId(article.getUuid()) > 0) {
                if (articleMapper.deleteByPrimaryKey(article.getUuid()) > 0) {
                    return Result.createSuccess("删除成功!,无法恢复文章");
                }
            } else {
                return Result.createError("删除失败");
            }
        }
        return Result.createError("非法操作");
    }


    @Override
    public Result<Page<Article>> getPageArticles1(String timeRange, String title, Integer type,
                                                  Integer pageIndex, Integer pageSize,
                                                  HttpSession session, boolean isDraft) {
        UserWithBLOBs loginUser = (UserWithBLOBs) session.getAttribute(BlogConstants.LOGIN_SESSION_KEY);
        Page<Article> page = new Page<Article>(pageIndex, pageSize);
        Map<String, Object> param = new HashMap<String, Object>();
        if (StringUtils.isNotBlank(timeRange)) {
            param.put("startTime", timeRange.split("~")[0]);
            param.put("endTime", timeRange.split("~")[1]);
        }
        param.put("title", title);
        param.put("userId", loginUser.getUuid());
        if (type != null) {
            param.put("type", type);
        }

        if (isDraft) {

            param.put("statusList", Arrays.asList(ArticleStatus.DRAFTS.getValue()));
        } else {
            param.put("statusList", ArticleStatus.getNotDraftStatus());
        }

        page.setCount(articleMapper.selectCount1(param));
        param.put("start", (pageIndex - 1) * pageSize);
        param.put("row", pageSize);
        page.setDataList(articleMapper.selectList1(param));
        return Result.createSuccess(page);
    }
    @Override
    public Result<Page<Article>> getPageWhisper(Integer pageIndex, Integer pageSize, HttpSession session, UserWithBLOBs user)
    {
        Page<Article> page = new Page<Article>(pageIndex, pageSize);
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("type", 1);
        param.put("userId", user.getUuid());
        param.put("statusList", ArticleStatus.getNotDraftStatus());
        page.setCount(articleMapper.selectCount1(param));
        param.put("start", (pageIndex - 1) * pageSize);
        param.put("row", pageSize);
        page.setDataList(articleMapper.selectList1(param));
        return Result.createSuccess(page);
    }

    @Override
    public ArticleWithBLOBs getArticleByld(String uuid) {
        return articleMapper.selectByPrimaryKey(uuid);
    }

    @Override
    public List<ArticleCheck> getArticleCheck(String uuid) {
        return articleCheckMapper.selectListByArticleByld(uuid);
    }

    @Override
    public Result updatePlusReader(String uuid) {
        ArticleWithBLOBs a = articleMapper.selectByPrimaryKey(uuid);
        if (a == null) {
            return Result.createError("此文章不存在");
        }
        a.setReader(a.getReader() + 1);
        if (articleMapper.updateByPrimaryKeySelective(a) > 0) {
            return Result.createSuccess("增加成功");
        }
        return Result.createError("增加失败");
    }
}
